package com.seeyon.ctp.rest.resources;

import com.seeyon.apps.addressbook.manager.AddressBookCustomerFieldInfoManager;
import com.seeyon.apps.addressbook.po.AddressBook;
import com.seeyon.apps.commonExt.util.CommonRestUtil;
import com.seeyon.apps.taxFund.api.ShuiJinEnum;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.V3xOrgAccount;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.organization.manager.OrgManagerDirect;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.*;

@Path("gk")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces(MediaType.APPLICATION_JSON)
public class GKUserSyncResource extends BaseResource {
	
	private OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
	private OrgManagerDirect orgManagerDirect = (OrgManagerDirect) AppContext.getBean("orgManagerDirect");

	private static final Logger logger = LoggerFactory.getLogger(GKUserSyncResource.class);
	
	@SuppressWarnings("unchecked")
	@POST
	@Produces({ MediaType.APPLICATION_JSON })
	@Path("user/syncAll")
	public Response userSyncAll(ArrayList<Map<String, Object>> params) throws BusinessException{
        try {
            Set<String> errors = new HashSet<>();
            for (V3xOrgAccount account : orgManager.getAllAccounts()) {
                String nsrsbh = Optional.ofNullable(((AddressBookCustomerFieldInfoManager) AppContext.getBean("addressBookCustomerFieldInfoManager"))
                                .getByMemberId(account.getId()))
                        .map(AddressBook::getExtAttr1)
                        .orElse(null);
                if (StrUtil.isBlank(nsrsbh)) {
                    continue;
                }
                List<V3xOrgMember> allMembers = orgManagerDirect.getAllMembers(account.getId(), false);
                for (V3xOrgMember member : allMembers) {
                    try {
                        Map<String, Object> apiParams = convertToParams(member);
                        apiParams.put("password", "123456");
                        CommonRestUtil.postValid(ShuiJinEnum.USER_SYNC, null, apiParams);
                    } catch (Exception e) {
                        errors.add(member.getLoginName());
                    }
                }
            }
            if (CollectionUtil.isNotEmpty(errors)) {
                return fail("部分人员同步失败：" + String.join(",", errors));
            }
            return success("同步成功");
        } catch (Exception e) {
            logger.error("人员全量同步服务异常", e);
           return fail("服务异常");
        }
    }

    private Map<String, Object> convertToParams(V3xOrgMember member) throws BusinessException {
        V3xOrgAccount account = orgManager.getAccountById(member.getOrgAccountId());
        Assert.notNull(account, "人员编号【{}】单位为空", member.getCode());

        String nsrsbh = Optional.ofNullable(((AddressBookCustomerFieldInfoManager) AppContext.getBean("addressBookCustomerFieldInfoManager"))
                        .getByMemberId(account.getId()))
                .map(AddressBook::getExtAttr1)
                .orElseThrow(() -> new BusinessException("人员编号【{}】税号为空", member.getCode()));

        boolean valid = member.getStatus() == 1 && member.getEnabled() && (!member.getIsDeleted()) && member.getState() == 1;

        Map<String, Object> params = new HashMap<>();
        params.put("account", member.getLoginName());

        params.put("name", member.getName());
        // 组织名称
        params.put("nsrmc", account.getName());
        // 组织税号
        params.put("nsrsbh", nsrsbh);
        params.put("status", valid ? 1 : 0);
        return params;
    }

}
